
const BASE_URL = 'https://www.oscjary.com'

const templateDic = {
  app: `${BASE_URL}/os-low-code/index.html`,
  formwork: `${BASE_URL}/os-low-code/templates/app-formwork/index.html`
}

function verifyOptions(options) {
  if (!options.containerId) {
    console.error('Need Id Of Dom Container')
  } else if (!options.template) {
    console.error('Need Target Of Template')
  } else {
    return true
  }

  return false
}

async function getHtmlText({ template = '' }) {
  let result = null
  try {
    result = await axios.get(templateDic[template]).then((res) => {
      if (res && res.status === 200 && res.data) {
        return res.data
      }
      return null
    })
  } catch (err) {
    result = null
  }

  return result
}

function loadHtml(html = '', options: any = {}) {
  return new Promise((resolve) => {
    const container = document.getElementById(options.containerId) as HTMLElement
    container.innerHTML = ''

    const htmlBox = document.createElement('div')
    htmlBox.innerHTML = html

    const htmlDiv = htmlBox.querySelector('div') as HTMLElement
    htmlDiv.setAttribute('data-containerId', options.containerId)

    const div = document.createElement('div')
    div.appendChild(htmlDiv)
    container.appendChild(div)

    const scriptList: any = htmlBox.getElementsByTagName('script')
    const linkList: any = htmlBox.getElementsByTagName('link')

    let loadLength = 0
    for (const script of scriptList) {
      const newScript = document.createElement('script')
      ;['type', 'src', 'crossorigin'].forEach((el) => {
        if (script.getAttribute(el)) {
          newScript.setAttribute(el, script.getAttribute(el))
        }
      })
      newScript.onload = () => {
        loadLength++
        if (loadLength === scriptList.length) {
          resolve(true)
        }
      }
      container.appendChild(newScript)
      container.removeChild(newScript)
    }

    for (const link of linkList) {
      const newLink = document.createElement('link')
      ;['rel', 'href', 'crossorigin'].forEach((el) => {
        if (link.getAttribute(el)) {
          newLink[el] = link.getAttribute(el)
        }
      })

      container.appendChild(newLink)
    }

    // @ts-ignore
    if (window.__os_low_code_render && window.__os_low_code_render[options.template]) {
      resolve(true)
    }
  })
}

export const run = async function (options = {}, callback = () => {}) {
  if (!verifyOptions(options)) {
    return
  }

  const html = await getHtmlText(options)
  if (!html) {
    console.error('Get Template Html Failed!!')
    return
  }

  await loadHtml(html, options)

  // @ts-ignore
  if (window.__os_low_code_render && window.__os_low_code_render[options.template]) {
    // @ts-ignore
    window.__os_low_code_render[options.template](options)
  }

  callback()
}
